$(function () {

    new AjaxUpload('#upload', {
        action: "/qiniu/upload",
        name: 'file',
        autoSubmit: true,
        responseType: "json",
        onSubmit: function (file, extension) {
            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))) {
                alert('只支持jpg、png、gif格式的图片！');
                return false;
            }
        },
        onComplete: function (file, r) {
            alert(r);
        }
    });

    $.ajax({
        url: "/qiniu/token", success: function (res) {
            var token = res;
            Qiniu.uploader({
                runtimes: 'html5,flash,html4',
                browse_button: 'upload2',
                flash_swf_url: './Moxie.swf',
                chunk_size: '4mb',
                unique_names: false,
                save_key: false,
                uptoken: token,
                domain: 'http://qiniu-plupload.qiniudn.com/',
                get_new_uptoken: false,
                multi_selection: 'false',
                auto_start: true,
                max_retries: 0,
                filters: {
                    prevent_duplicates: false
                },
                init: {
                    FilesAdded: function (up, files) {
                        var length = files.length;
                        for (var i = 0; i < length; i++) {
                            var item = files[i]
                            if (item.size > (200 * 1024)) {
                                alert("文件大于200K，请处理后再上传");
                                up.removeFile(item)
                            }
                        }
                    },
                    BeforeUpload: function (up, file) {
                    },
                    UploadProgress: function (up, file) {
                    },
                    FileUploaded: function (up, file, info) {
                        var res = JSON.parse(info);
                        //判断是否成功
                        alert(info);
                    },
                    Error: function (up, err, errTip) {
                        this.uploadStatus = 'failed';
                        alert("error上传失败，请重新上传");
                    },
                    Key: function (up, file) {
                        var start = file.name.lastIndexOf(".");
                        var end = file.name.length
                        var suffix = file.name.substring(start, end);
                        var prefix = "upload";
                        var uuid = guuid(prefix);
                        return prefix + '/' + uuid + suffix;
                    }
                }
            });
        }
    });

});

function guuid(prefix) {
    var counter = 0;
    var guid = (+new Date()).toString(32),
        i = 0;

    for (; i < 5; i++) {
        guid += Math.floor(Math.random() * 65535).toString(32);
    }

    return (prefix || 'wu_') + guid + (counter++).toString(32);
}
